/**
 * Created by henian.xu on 2017/3/29.
 *
 */

(function ($) {
  var
    plugName = 'popup',
    plugVersion = '0.1.0';

  $[plugName] = function (el, options) {
    var
      $target = $(el),
      cfg = $.extend(true, {}, $[plugName].defaults, options),
      method = {};
    var
      targetId = $target.data('target'),
      $popup = $(targetId),
      $body = $(document.body);

    //缓存实例对象
    $target.data('zte-' + plugName, $target);

    method = {
      init: function () {
        method.eventInit();
        method.onClickTarget();
      },
      //事件绑定
      eventInit: function () {
        $target.on('click', method.onClick);
        $popup.on('click', '.close', method.onclose)
      },
      //被惰性创建的实例
      onClickTarget: function () {
        method.onClick();
      },
      //目标被点击
      onClick: function (e) {
        var isShow = $popup.is(':visible');
        if (isShow)return;
        $popup.show();
        $body.css('overflow','hidden');
      },
      //关闭事件
      onclose: function () {
        $popup.hide();
        $body.css('overflow','');
      }

    };

    method.init();
  };

  $[plugName].defaults = {
    clickTarget: null//惰性加载被点击目标
  };

  $.fn[plugName] = function (options) {
    options = options || {};
    if (typeof options === 'object') {
      return this.each(function () {
        var $plug = $(this).data('zte-' + plugName);
        if ($plug === undefined) {
          //创建实例对象
          new $[plugName](this, options);
        } else {
          //实例对象已存在
        }
      })
    } else {
      //其它参数类型
    }

  };

  //惰性加载用法
  $(document).delegate('[data-action="popup"]', 'click', function (e) {
    var $target = $(e.target);
    if ($(this).data('zte-' + plugName) !== undefined) {
      return;
    } else {
      new $[plugName](this, {clickTarget: true});
    }
    console.log($target);
  });

  return $[plugName];
})(jQuery);